package com.lanxum.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lanxum.common.constant.Constant;
import com.lanxum.common.controller.Base;
import com.lanxum.common.enums.CommonEnum;
import com.lanxum.common.task.AsyncPdfTaskService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @author li.sun
 * @Description:
 * @date 2020/10/18 20:52
 */
public class PdfUtil extends Base {

    private static final Logger logger = LoggerFactory.getLogger(PdfUtil.class);

    public static void main(String[] args) {
        System.out.println(Float.valueOf(30));

        String barcodeData = "{\n" +
                "\n" +
                "\t\"copies\": \"1\",\n" +
                "\t\"pages\": \"3\",\n" +
                "\t\"fileName\": \"123.pdf\",\n" +
                "\t\"pdfData\": {\n" +
                "\t\t\"filePath\": \"C:/Users/Lenovo/Desktop/li.sun\",\n" +
                "\t\t\"paperSize\": \"A4\",\n" +
                "\t\t\"outPdfFilePath\": \"D:/opt/DYSJ/printJava/puf\",\n" +
                "\t\t\"outPdfFileName\": \"123444.pdf\",\n" +
                "\t\t\"duplex\": \"1\",\n" +
                "\t\t\"imagePosition\": \"bottom-right\",\n" +
                "\t\t\"orientation\": \"0\",\n" +
                "\t\t\"shiftAdjustmentX\": \"0\",\n" +
                "\t\t\"shiftAdjustmentY\": \"10\",\n" +
                "\t\t\"width\": \"180\",\n" +
                "\t\t\"height\": \"50\"\n" +
                "\t},\n" +
                "\t\"barcodeData\": {\n" +
                "\t\t\"outBarcodePngPath\": \"D:/opt/DYSJ/printJava/barcode/png\",\n" +
                "\t\t\"imageContent\": \"D-密级-用户名称-部门名称-20201017222740\",\n" +
                "\t\t\"textContent\": \"D-密级-用户名称-部门名称-20201017222740\",\n" +
                "\t\t\"textFontSize\": \"15\",\n" +
                "\t\t\"barcodeType\": \"0\",\n" +
                "\t\t\"scaling\": \"4\"\n" +
                "\t}\n" +
                "}";
        try {
            String result = new PdfUtil().pdfImportBarcode(barcodeData);
            System.out.println(result);
            System.exit(0);
        } catch (Exception e) {
            logger.error("PDF嵌入条码异常－Exception:{}", e);
        }
    }

    public static String pdfImportBarcode(String pdfData) throws Exception {
        String outPdfFilePath;
        String outPdfFileName;
        String resultPdf;
        String barcodeStr = null;
        List<String> copiesList = new ArrayList<>();
        try {
            barcodeStr = BarcodeUtil.createBarcodeImg(pdfData);
            if (StringUtils.isNotBlank(barcodeStr)) {
                JSONObject barcodeJson = JSONObject.parseObject(barcodeStr);
                if (!StringUtils.equals(CommonEnum.SUCCESS.getCode(), barcodeJson.getString("code"))) {
                    return barcodeStr;
                }
            }

            String validatePdfResult = validatePdfParam(pdfData);
            if (StringUtils.isNotBlank(validatePdfResult)) {
                return validatePdfResult;
            }
            JSONObject rootJson = JSON.parseObject(pdfData);
            String copies = rootJson.getString("copies");
            String fileName = rootJson.getString("fileName");
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            JSONObject pdfDataJson = rootJson.getJSONObject("pdfData");
            outPdfFilePath = pdfDataJson.getString("outPdfFilePath");
            File outPdfFilePathFile = new File(outPdfFilePath);
            if (!outPdfFilePathFile.exists())
                outPdfFilePathFile.mkdirs();
            outPdfFileName = pdfDataJson.getString("outPdfFileName");

            //如果是多份，用于存储多个pdf文件路径用于合并
            String[] pdfPaths = new String[Integer.parseInt(copies)];
            AsyncPdfTaskService asyncPdfTaskService = new AsyncPdfTaskService();
            for (int i = 0; i < Integer.parseInt(copies); i++) {
                String copiesNumber = CommonUtil.handleCopiesPages(copies, i + 1);
                //一份嵌条码pdf文件路径
                String outPdfFilePathCopies = outPdfFilePath + File.separator + fileName + copiesNumber + ".pdf";
                String outPdfFilePathCopiesTemp = outPdfFilePath + File.separator + fileName + "_" + copiesNumber + ".pdf";
                copiesList.add(outPdfFilePathCopies);
                copiesList.add(outPdfFilePathCopiesTemp);
                Future future = asyncPdfTaskService.submit(pdfData, outPdfFilePath, i + 1);
                if (future != null) {
                    JSONObject jsonObject = (JSONObject) future.get();
                    pdfPaths[i] = jsonObject.getString("outPdfFilePathCopies");
                }
            }

            // 根据份文件，进行合并
            resultPdf = outPdfFilePath + File.separator + outPdfFileName;
            FileUtil.mergePdfFiles(pdfPaths, resultPdf);

        } catch (Exception e) {
            logger.error("PdfUtil.pdfImportBarcode--Exception:{}", e);
            return null;
        } finally {
            // 删除已嵌入完成的二维码图片
            deleteBarcodeImage(barcodeStr);
            deleteTempFile(copiesList);
        }

        logger.info("嵌入完成的PDF路径和名称，outPdfFilePath：{}，outPdfFileName：{}", outPdfFilePath, outPdfFileName);
        return respJson(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getMessage(), resultPdf);
//        return resultPdf;
    }

    private static String validatePdfParam(String pdfData) {
        if (StringUtils.isBlank(pdfData)) {
            return respJson(CommonEnum.PARAM_NULL_ERROR);
        }
        JSONObject rootJson = null;
        JSONObject pdfDataJson = null;
        try {
            rootJson = JSONObject.parseObject(pdfData);
            if (null == rootJson) {
                return respJson(CommonEnum.PARAM_ERROR, Constant.PDF_IMPORT_BARCODE_EXAMPLE);
            }
            if (!rootJson.containsKey("pdfData")) {
                return respJson(CommonEnum.PARAM_NULL_ERROR, "barcodeData:PDF数据不存在");
            }
            pdfDataJson = rootJson.getJSONObject("pdfData");
        } catch (Exception e) {
            return respJson(CommonEnum.PARAM_ERROR, Constant.PDF_IMPORT_BARCODE_EXAMPLE);
        }

        if (!pdfDataJson.containsKey("filePath") || StringUtils.isBlank(pdfDataJson.getString("filePath"))) {
            return respJson(CommonEnum.PARAM_NULL_ERROR, "filePath:PDF文件路径, " + CommonEnum.PARAM_NULL_ERROR.getMessage());
        }

        if (!pdfDataJson.containsKey("paperSize") || StringUtils.isBlank(pdfDataJson.getString("paperSize"))) {
            return respJson(CommonEnum.PARAM_NULL_ERROR, "paperSize:纸型, " + CommonEnum.PARAM_NULL_ERROR.getMessage());
        }

        if (!pdfDataJson.containsKey("outPdfFilePath") || StringUtils.isBlank(pdfDataJson.getString("outPdfFilePath"))) {
            return respJson(CommonEnum.PARAM_NULL_ERROR, "copoutPdfFilePathies:嵌入条码后的PDF文件路径, " + CommonEnum.PARAM_NULL_ERROR.getMessage());
        }

        if (!pdfDataJson.containsKey("outPdfFileName") || StringUtils.isBlank(pdfDataJson.getString("outPdfFileName"))) {
            return respJson(CommonEnum.PARAM_NULL_ERROR, "outPdfFileName:嵌入条码后的PDF文件名称, " + CommonEnum.PARAM_NULL_ERROR.getMessage());
        }

        return null;
    }

    /**
     * 删除已嵌入完成的二维码图片
     *
     * @param barcodeStr
     */
    private static void deleteBarcodeImage(String barcodeStr) {
        if (StringUtils.isNotBlank(barcodeStr)) {
            JSONObject barcodeJson = JSONObject.parseObject(barcodeStr);
            JSONObject dataJson = barcodeJson.getJSONObject("data");
            if (null != dataJson) {
                File file = null;
                for (Map.Entry<String, Object> entry : dataJson.entrySet()) {
                    String value = (String) entry.getValue();
                    if (StringUtils.isNotBlank(value)) {
                        file = new File(value);
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                }
            }
        }
    }


    /**
     * 删除临时文件
     * @param copiesList
     */
    private static void deleteTempFile(List<String> copiesList) {
        logger.info("--"+JSON.toJSONString(copiesList));
        if (CollectionUtils.isNotEmpty(copiesList)) {
            for (String str : copiesList) {
                File file = new File(str);
                if (file.exists())
                    file.delete();
            }
        }
    }

}
